package org.list.concurrency;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListConcurrency {

    private static List<String> list = new ArrayList<>();


    public static void main(String[] args) {

        new Thread(new Runnable() {

            String latestEle = null;
            volatile int listSize;
            Map<Integer, Integer> map = new HashMap<>();

            @Override
            public void run() {
                System.out.println("zkWatcher监控线程执行了");

                /*
zk监控到null元素:null
zk监控获取到最后元素是:A14998
zk监控到null元素:null
zk监控获取到最后元素是:A24997
zk监控到null元素:null
zk监控获取到最后元素是:A39998
zk监控获取到最后元素是:A39999
                 */
                while (true) {
                    if (getListSize() != 0) {
                        latestEle = list.get(getListSize() - 1);
                        if (!map.keySet().contains(getListSize())) {
                            map.put(getListSize(), 1);
//                            System.out.print("\nzk监控获取到最后元素是:" + this.latestEle );
                            if (getListSize() % 5000 == 0) {
                                System.out.print("\nzk监控获取到最后元素是:" + this.latestEle);
                            }
                        }

                        if (latestEle == null) {
                            System.out.print("\nzk监控到null元素:" + this.latestEle);
                        }

//                        try {
//                            Thread.sleep(1L);
//                        } catch (InterruptedException e) {
//                            throw new RuntimeException(e);
//                        }
                    }
                }

            }

            public int getListSize() {
                listSize = list.size();
                return listSize;
            }
        }).start();

        System.out.println("主线程执行了");
        for (int i = 0; i < 1_000_000; i++) {
            list.add("A" + i);
        }
    }
}
